package com.ztesoft.web.baseconfig.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ztesoft.core.common.Page;
import com.ztesoft.framework.exception.BaseAppException;
import com.ztesoft.framework.log.ZTEsoftLogManager;
import com.ztesoft.framework.util.JsonUtil;
import com.ztesoft.framework.util.Utils;
import com.ztesoft.web.baseconfig.db.po.ColumnNamePO;
import com.ztesoft.web.baseconfig.db.po.DmSrcTablePO;
import com.ztesoft.web.baseconfig.db.po.DmStrategyPO;
import com.ztesoft.web.baseconfig.db.po.DmTargetTablePO;
import com.ztesoft.web.baseconfig.db.po.SubTablePO;
import com.ztesoft.web.baseconfig.db.po.TableNamePO;
import com.ztesoft.web.baseconfig.db.po.TargetTablePO;
import com.ztesoft.web.baseconfig.service.IDmSrcTableService;
import com.ztesoft.web.baseconfig.service.IDmStrategyService;
import com.ztesoft.web.baseconfig.service.IDmTargetTableService;
import com.ztesoft.web.common.DMSConstant.Status;

/**
 * <Description>dmtargettable管理 <br>
 * 
 * @author codeCreater <br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2014年11月11日 <br>
 * @since V1.0<br>
 * @see com.ztesoft.web.baseconfig.controller <br>
 */

@Controller
@RequestMapping("/baseconfig/dmtargettable")
public class DmTargetTableController {

	private static final ZTEsoftLogManager logger = ZTEsoftLogManager.getLogger(DmTargetTableController.class);

	@Autowired
	private IDmTargetTableService dmTargetTableService;
	@Autowired
	private IDmSrcTableService dmSrcTableService;
	@Autowired
	private IDmStrategyService dmStrategyService;

	@RequestMapping("index")
	public String index(Model model) {
		// ///////
		// TODO 根据业务场景，进行条件分支跳转、设置页面默认值等

		// ///////

		return "cleaner/baseconfig/jsp/dmTargetTable";
	}

	@RequestMapping("queryRecordByPage")
	@ResponseBody
	public Page<DmTargetTablePO> queryRecordByPage(DmTargetTablePO record, Page<DmTargetTablePO> resultPage)
			throws BaseAppException {
		resultPage = dmTargetTableService.selectByArgAndPage(record, resultPage);
		return resultPage;
	}

	@RequestMapping("add")
	@ResponseBody
	public DmTargetTablePO add(DmTargetTablePO record) throws BaseAppException {
		logger.debug("add record begin...record=[{0}]", record);
		dmTargetTableService.add(record);
		return record;
	}

	/**
	 * 目标表验证按钮，验证目标表是否存在，并配置字段映射
	 * 
	 * @param dstPO
	 *            ,dttPO
	 * @return
	 * @throws BaseAppException
	 */
	@RequestMapping("stColumnsRelation")
	@ResponseBody
	public DmTargetTablePO stColumnsRelation(DmTargetTablePO dttPO) throws BaseAppException {
		logger.debug("begin...dttPO=[{0}]", dttPO);
		return dmTargetTableService.stColumnsRelation(dttPO);
	}

	@RequestMapping("addForDraft")
	@ResponseBody
	public DmStrategyPO addForDraft(DmTargetTablePO dttPO, DmSrcTablePO dstPO) throws BaseAppException, Exception {
		DmStrategyPO dsPO = new DmStrategyPO();
		// 源表
		dstPO.setTableNameArray(JsonUtil.toArray(dstPO.getTableName(), TableNamePO.class));
		if (!"[null]".equals(dstPO.getSubTablesStr())) {
			dstPO.setSubTables(JsonUtil.toList(dstPO.getSubTablesStr(), SubTablePO.class));
		}
		List<SubTablePO> subTablePOList = dstPO.getSubTables();
		if (Utils.notEmpty(subTablePOList)) {
			for (int i = 0; i < subTablePOList.size(); i++) {
				if (Utils.isEmpty(subTablePOList.get(i))) {
					subTablePOList.remove(i);
					i--;
					continue;
				}
				subTablePOList.get(i).setSubTableNames(
						JsonUtil.toArray(subTablePOList.get(i).getSubTableName(), TableNamePO.class));
			}
		}
		dsPO = dmStrategyService.addSomeInfoOfOneStrategy(dstPO, Status.DRAFT.toString());
		// 目标表
		dttPO.setTargetTables(JsonUtil.toList(dttPO.getTargetTableStr(), TargetTablePO.class));
		dttPO.setTargetColMapList(JsonUtil.toList(dttPO.getTargetColMaps(), Object.class));
		List<TargetTablePO> targetTablePOList = dttPO.getTargetTables();
		for (int i = 0; i < targetTablePOList.size(); i++) {
			if ("".equals(targetTablePOList.get(i).getSrcTableName())) {
				targetTablePOList.remove(i);
				break;
			}
			targetTablePOList.get(i).setTargetTableNamePO(
					JsonUtil.toArray(targetTablePOList.get(i).getTargetTableName(), TableNamePO.class));
		}
		List<TargetTablePO> ttPOList = dmTargetTableService.addWithOther(dttPO, Status.DRAFT.toString());
		List<DmTargetTablePO> dttPOList = new ArrayList<DmTargetTablePO>();
		for (TargetTablePO ttPO : ttPOList) {
			DmTargetTablePO dttPO_0 = new DmTargetTablePO();
			dttPO_0.setTargetDataId(ttPO.getTargetDataId());
			dttPO_0.setTableName(ttPO.getTargetTableNamePO()[0].getValue());
			dttPOList.add(dttPO_0);
		}
		dsPO.setDmTargetTablePOList(dttPOList);
		return dsPO;
	}

	/**
	 * 验证表名是否存在，目标表表名控件，返回字段
	 * 
	 * @param record
	 * @return -1：已经配置过该表，-2：所选数据库中不存在该表
	 * @throws BaseAppException
	 */
	@RequestMapping("verifyTableName")
	@ResponseBody
	public DmTargetTablePO verifyTableName(DmTargetTablePO record) throws BaseAppException, Exception {
		record.setTableNames(JsonUtil.toArray(record.getTableName(), TableNamePO.class));
		String tableName = record.getTableNames()[0].getValue();
		record.setTableName(tableName);
		if (record.getIsEdit() == 0 && dmTargetTableService.selectByTableName(record).size() != 0) {// 已经配置过该表
			record.setSourceDataId(-1);
			return record;
		}
		ColumnNamePO[] allColumns = dmSrcTableService.selectAllColumns(record.getDbLinkId(), record.getDbUserName(),
				tableName);
		if (allColumns.length == 0) {// 所选数据库中不存在该表
			record.setSourceDataId(-2);
			return record;
		}
		if ("-2".equals(allColumns[0].getValue()) && "-2".equals(allColumns[0].getColumnName())) {
			record.setSourceDataId(-2);
			return record;
		}
		record.setAllColumns(allColumns);
		return record;
	}

	@RequestMapping("update")
	@ResponseBody
	public DmTargetTablePO update(DmTargetTablePO record) throws BaseAppException {
		logger.debug("modify record begin...record=[{0}]", record);
		dmTargetTableService.update(record);
		return record;
	}

	@RequestMapping("delete")
	@ResponseBody
	public int delete(DmTargetTablePO record) throws BaseAppException {
		logger.debug("delete record begin...record=[{0}]", record);
		return dmTargetTableService.delete(record);
	}

	@RequestMapping("qryRecordInfo")
	@ResponseBody
	public DmTargetTablePO qryRecordInfo(@RequestParam(value = "targetDataId", required = true) Integer targetDataId)
			throws BaseAppException {
		DmTargetTablePO record = dmTargetTableService.selectByPrimaryKey(targetDataId);
		return record;
	}

}
